package com.weng.coder.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.weng.coder.common.CommonProperties;
import com.weng.coder.common.utils.Constants;
import com.weng.coder.common.utils.FileUtil;
import com.weng.coder.entity.Project;
import com.weng.coder.entity.Template;
import com.weng.coder.service.ProjectService;
import com.weng.coder.service.TemplateService;
import com.weng.framework.core.model.ResponseData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 代码模板 Web API
 *
 * @作者 wengzhonghui
 * @创建时间 2018-02-25 15:49:52
 */
@RestController
@RequestMapping("/template")
@Api(value = "代码模板相关接口", tags = {"代码模板相关接口"})
@Slf4j
public class TemplateController{
	@Resource
	private TemplateService templateService;

	@Resource
	private ProjectService projectService;
	
	/**
     * 下载模板
     * 
     * @author wengzhonghui 2017年7月12日
     * @param response
     * @throws UnsupportedEncodingException
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    @ApiOperation(value = "", notes = "")
    public void download( String templateId, HttpServletResponse response) throws UnsupportedEncodingException, IOException {
    	Template template = this.templateService.getOne(templateId);
    	byte[] data = template.getContent().getBytes("UTF-8");
        response.setContentType("application/x-msdownload; charset=UTF-8");
        response.setContentLength(data.length);
        response.setHeader("Content-Disposition", "attachment; filename=" + template.getName() + ".ftl");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(data);
        outputStream.flush();
        outputStream.close();
    }
    
	 /**
	 * 获取分页数据
	 */
	 @ResponseBody
	 @RequestMapping(value="/list",method=RequestMethod.GET)
	 @ApiOperation(value = "分页获取代码模板列表", notes = "分页获取代码模板列表")
	 @ApiImplicitParams({
        @ApiImplicitParam(paramType = "query",name = "pageNo",dataType ="Integer" ,required = true,value = "页数"),
        @ApiImplicitParam(paramType = "query",name = "pageSize",dataType ="Integer" ,required = true,value = "每页数量")
	 })
	 public ResponseData getDataByPage(Integer pageNo, Integer pageSize, String name, String code
					 , String projectId)throws Exception{
		 Template template = new Template();		 
		 template.setName(name);
		 template.setCode(code);
		 template.setProjectId(projectId);
		 IPage<Template> page = templateService.getDataByPage(pageNo, pageSize, template);
		 return ResponseData.success(page);
	 }
	
	 /**
	 * 获取代码模板
	 * 
	 */
	@RequestMapping(value="get-one",method=RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "获取代码模板", notes = "获取代码模板")
	public ResponseData getTemplate(String id, Model model
			,HttpServletRequest request) throws Exception{
		if(StringUtils.isEmpty(id)){
			return ResponseData.failed("代码模板Id不能为空！");
		}
		
		Template template = this.templateService.getOne(id);
		return ResponseData.success(template);
	}
	 
	/**
	 * 添加代码模板
	 * 
	 */
	@RequestMapping(value="add",method=RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "添加代码模板", notes = "添加代码模板")
	public ResponseData addTemplate(Template template,String filePath, Model model
			,HttpServletRequest request) throws Exception{
		if(template==null ){
			return ResponseData.failed("代码模板不能为空！");
		}
		Project project = this.projectService.getOne(template.getProjectId());
		if(project==null){
			return ResponseData.failed("添加失败，项目不存在或已经被删除！");
		}else if(project.getIsBuildIn()!=null 
				&& Constants.IS_BUILD_IN_TRUE.compareTo(project.getIsBuildIn())==0){
			return ResponseData.failed("添加失败，该项目是示例模板项目，不允许修改，请在个人项目中修改！");
		}
		
		if(!StringUtils.isEmpty(filePath)){
			String content = new String(FileUtil.fileToBytes(filePath), Constants.SYSTEM_CHAR_CODE);
			template.setContent(content);
		}
		templateService.save(template);
		request.setAttribute(Constants.AOP_LOG_DESCRIPTION, "添加代码模板，【"+template.getId()+"】");
		return ResponseData.success("添加代码模板成功！");
	}
	
	/**
	 * 更新代码模板
	 */
	@RequestMapping(value="update",method=RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "更新代码模板", notes = "更新代码模板")
	public ResponseData updateTemplate(Template template,String filePath,HttpServletRequest request) throws Exception{
		if(template==null ){
			return ResponseData.failed("代码模板不能为空！");
		}
//		Template oldTemplate = this.templateService.getOne(template.getId());
//		if(!StringUtils.isEmpty(filePath)){
//			String content = new String(FileUtil.fileToBytes(filePath), Constants.SYSTEM_CHAR_CODE);
//			template.setContent(content);
//		}else{
//			template.setContent(oldTemplate.getContent());
//		}
		Project project = this.projectService.getOne(template.getProjectId());
		if(project==null){
			return ResponseData.failed("更新失败，项目不存在或已经被删除！");
		}else if(project.getIsBuildIn()!=null 
				&& Constants.IS_BUILD_IN_TRUE.compareTo(project.getIsBuildIn())==0){
			return ResponseData.failed("更新失败，该项目是示例模板项目，不允许修改，请在个人项目中修改！");
		}
		templateService.save(template);
		request.setAttribute(Constants.AOP_LOG_DESCRIPTION, "更新代码模板，账号【"+template.getId()+"】");
		return ResponseData.success("更新成功！");
	}
	
	
	/**
	 * 删除代码模板
	 */
	@RequestMapping(value="delete",method=RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "删除代码模板", notes = "删除代码模板,多个ID以,号分隔")
	@Transactional
	public  ResponseData deletetemplate( String ids
			,HttpServletRequest request) throws Exception{
		String[] templateIdList = ids.split(",");
		if(templateIdList == null || templateIdList.length < 1){
			return ResponseData.failed("代码模板ID不能为空");
		}
		StringBuilder logDesc = new StringBuilder();
		List<Template> templateList = templateService.findByIds(Arrays.asList(templateIdList));
		if(templateList!=null && templateList.size()>0){
			for(Template template:templateList){
				Project project = this.projectService.getOne(template.getProjectId());
				if(project==null){
					return ResponseData.failed("更新失败，项目不存在或已经被删除！");
				}else if(project.getIsBuildIn()!=null 
						&& Constants.IS_BUILD_IN_TRUE.compareTo(project.getIsBuildIn())==0){
					return ResponseData.failed("删除失败，该项目是示例模板项目，不允许修改，请在个人项目中操作！");
				}
				if(logDesc.length()>0){
					logDesc.append(",");
				}
				logDesc.append(template.getId());
				this.templateService.delete(template);
			}
			request.setAttribute(Constants.AOP_LOG_DESCRIPTION, "删除代码模板【"+logDesc.toString()+"】");
		}
		return ResponseData.success("删除成功");
	}


	@ApiOperation(value = "上传代码模板", notes = "上传代码模板")
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData upload(HttpServletRequest request,HttpServletResponse response
			,@RequestParam(value = "file",required = false) MultipartFile file1) throws UnsupportedEncodingException{
        MultipartFile file = null;

        if (file1 != null) {
            file = file1;
        } 

		if(file==null || file.getSize()==0){
			return ResponseData.failed("文件不能为空！");
		}
		request.setCharacterEncoding(Constants.SYSTEM_CHAR_CODE); // 设置编码
		response.setCharacterEncoding(Constants.SYSTEM_CHAR_CODE);
		String filename = file.getOriginalFilename();
		response.setContentType("text/html;charset="+Constants.SYSTEM_CHAR_CODE);
		filename = new Date().getTime() + filename.substring(filename.lastIndexOf("."));
		String targetPath =  CommonProperties.generateExcelPath + File.separator;
		File tarFile = new File(targetPath);
		if(!tarFile.exists()){
			tarFile.mkdirs();
		}
		File targetFile = new File(targetPath, filename);
		try {
			FileUtil.copy(file.getInputStream(), targetFile);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
		return ResponseData.success(targetFile.getAbsolutePath());
	}
	
	@ApiOperation(value = "获取项目ID获取ID和模板名称列表", notes = "获取项目ID获取ID和模板名称列表")
	@RequestMapping(value = "/getIdsAndNames", method = RequestMethod.GET)
	@ResponseBody
	public ResponseData getIdsAndNames(String projectId){
		return ResponseData.success(this.templateService.getIdsAndNames(projectId));
	}
}

